<template>
  <div class="listViewContainer">
    <Scroll
      class="listView"
      :data="data"
      ref="listView"
      :listenScroll="listenScroll"
      :probeType="3"
      @scroll="scroll"
    >
      <ul>
        <li v-for="(group,index) in data" class="list-group" :key="index" ref="listGroup">
          <h2 class="list-group-title">{{group.title}}</h2>
          <ul>
            <li
              v-for="(item, index) in group.items"
              :key="index"
              class="list-group-item"
              @click="toSingeritem(item)"
            >
              <img class="avatar" v-lazy="item.avatar" />
              <span class="name">{{item.name}}</span>
            </li>
          </ul>
        </li>
      </ul>
      <div
        class="list-shortcut"
        @touchstart.stop.prevent="onShortcutTouchStart"
        @touchmove.stop.prevent="onShortcutTouchMove"
      >
        <ul>
          <li
            v-for="(short, index) in shortcutList"
            :key="index"
            class="item"
            :data-index="index"
            :class="{'current': currentIndex === index}"
          >{{short}}</li>
        </ul>
      </div>
      <div class="list-fixed" v-show="fixedTitle">
        <h1 class="fixed-title">{{fixedTitle}}</h1>
      </div>
    </Scroll>
  </div>
</template>
<script>
import Scroll from "@/base/scroll/scroll";
import { getData } from "@/common/js/dom.js";

export default {
  data() {
    return {
      scrollY: -1, //实时滚动的位置，监测
      currentIndex: 0 //右边的通讯录的当前高亮的下标，默认是第一个高亮
    };
  },
  props: {
    data: {
      type: Array,
      default: []
    }
  },
  components: {
    Scroll
  },
  computed: {
    // 计算右边的通讯录
    shortcutList() {
      return this.data.map(group => {
        return group.title.substr(0, 1);
      });
    },
    //计算固定的title
    fixedTitle() {
      if (this.scrollY > 0) {
        return "";
      }
      return this.data[this.currentIndex]
        ? this.data[this.currentIndex].title
        : "";
    }
  },
  created() {
    this.touch = {}; //给this对象添加一个新的属性touch
    this.listenScroll = true;
    this.listHeight = []; //存放热门---A-Z每个分组的高度的数组
  },
  methods: {
    //给父组件暴露一个refresh,重新加载,方便父组件的mixin使用
    refresh() {
      this.$refs.listView.refresh();
    },
    //点击歌手行，跳转到歌手详情页
    toSingeritem(singeritem) {
      //事件派发出去，父组件接收
      this.$emit("select", singeritem);
    },
    //点击右边的通讯录,左边的列表也要滑动到相应的位置
    onShortcutTouchStart(e) {
      let anchorIndex = getData(e.target, "index");
      let fistTouch_S = e.touches[0];
      // 记录当前的Y偏移
      this.touch.y1 = fistTouch_S.pageY;
      // 记录当前的index
      this.touch.anchorIndex = anchorIndex;
      this._ScrollTo(anchorIndex);
    },
    //滑动右边的通讯录，左边的列表也要滑动到相应的位置
    onShortcutTouchMove(e) {
      let fistTouch_M = e.touches[0];
      this.touch.y2 = fistTouch_M.pageY;
      // 这样计算，就知道我们偏移了几个锚点，|0 和math.floor向上取整的效果一样的
      let delta = ((this.touch.y2 - this.touch.y1) / ANCHOR_HEIGHT) | 0;
      //计算当前滑动的下标,如果不转换成int型，相加还是字符串，滑动不到相应的位置的
      let anchorIndex = parseInt(this.touch.anchorIndex) + delta;
      this._ScrollTo(anchorIndex);
    },
    scroll(pos) {
      this.scrollY = pos.y;
    },
    //左边滚动到相应的下标位置的公共函数
    _ScrollTo(index) {
      if (!index && index !== 0) {
        return;
      }
      if (index < 0) {
        index = 0;
      } else if (index > this.listHeight.length - 2) {
        index = this.listHeight.length - 2;
      }
      //点击时，手动得到元素上限height位置，改变scrollY,使点击项高亮
      this.scrollY = -this.listHeight[index];
      // 第二个参数表示：要不要滚动动画缓动时间；0是瞬间滚动
      this.$refs.listView.scrollToElement(this.$refs.listGroup[index], 0);
    },
    //计算左边的每个list-group的高度
    _calculateHeight() {
      this.listHeight = []; //每次重新计算每个group高度时，恢复初始值
      const list = this.$refs.listGroup;
      let height = 0; //初始位置的height为0
      this.listHeight.push(height);
      for (let i = 0; i < list.length; i++) {
        let item = list[i]; //得到每一个group元素
        // 因为item是dom元素，可以直接通过clientHeight获取高度
        height += item.clientHeight;
        // 一个组里的li的高度相加，就是这个组的高度了
        this.listHeight.push(height); //得到每一个元素对应的height
      }
    }
  },
  watch: {
    //监听data是否发生变化
    data() {
      // 发生变化就延时计算一下（因为数据的变化到dom的变化需要一个过程）
      setTimeout(() => {
        this._calculateHeight();
      }, 20);
    },
    //监听scrollY是否变化
    scrollY(newY) {
      const listHeight = this.listHeight;
      // 当滚动到顶部，newY > 0
      if (newY >= 0) {
        //   console.log(newY)
        this.currentIndex = 0;
        return;
      }
      // 在中间部分滚动，遍历到最后一个元素，保证一定有下限，listHeight中的height比元素多一个
      for (let i = 0; i < listHeight.length - 1; i++) {
        // 上限
        let height1 = listHeight[i];
        // 下限
        let height2 = listHeight[i + 1];
        // 因为newY是负值，-newY才是正值
        if (-newY >= height1 && -newY < height2) {
          this.currentIndex = i;
          return;
        }
      }
      // 当滚动到底部，且-newY大于最后一个元素的上限
      // currentIndex 比listHeight中的height多一个，比元素多两个
      this.currentIndex = listHeight.length - 2;
      console.log(this.currentIndex);
    }
  }
};
</script>
<style lang="stylus" scoped>
@import '~@/common/stylus/variable.styl';
@import '../../common/stylus/variable';

.listViewContainer {
  width: 100%;
  height: 100vh;
  overflow hidden
}

.listView {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: $color-background;

  .list-group {
    padding-bottom: 30px;

    .list-group-title {
      height: 30px;
      line-height: 30px;
      padding-left: 20px;
      font-size: $font-size-small;
      color: $color-text-l;
      background: $color-highlight-background;
    }

    .list-group-item {
      display: flex;
      align-items: center;
      padding: 20px 0 0 30px;

      .avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
      }

      .name {
        margin-left: 20px;
        color: $color-text-l;
        font-size: $font-size-medium;
      }
    }
  }

  .list-shortcut {
    position: absolute; // 绝对定位到右侧
    right: 0;
    top: 50%;
    z-index: 30;
    transform: translateY(-50%);
    width: 20px;
    padding: 20px 0;
    border-radius: 10px;
    text-align: center;
    background: $color-background-d;
    font-family: Helvetica;

    .item {
      padding: 3px;
      line-height: 1;
      color: $color-text-l;
      font-size: $font-size-small;
      list-style: none;

      &.current {
        color: $color-theme;
      }
    }
  }

  .list-fixed {
    position: absolute; // 绝对定位到顶部
    top: -1px;
    left: 0;
    width: 100%;

    .fixed-title {
      height: 30px;
      line-height: 30px;
      padding-left: 20px;
      font-size: $font-size-small;
      color: $color-text-l;
      background: $color-highlight-background;
    }
  }

  .loading-container {
    position: absolute;
    width: 100%;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>